// options.js（完整修复版）
document.addEventListener('DOMContentLoaded', () => {
  // 加载已允许的域名列表
  loadAllowedDomains();
  
  // 添加按钮点击事件
  document.getElementById('add-domain-btn').addEventListener('click', addDomain);
  
  // 输入框回车事件
  document.getElementById('domain-input').addEventListener('keypress', (e) => {
    if (e.key === 'Enter') {
      addDomain();
    }
  });
  
  // 批量添加按钮事件 TODO
//   document.getElementById('batch-add-btn').addEventListener('click', toggleBatchMode);
  
//   // 批量添加区域取消按钮
//   document.getElementById('batch-cancel-btn').addEventListener('click', toggleBatchMode);
  
//   // 批量添加提交按钮
//   document.getElementById('batch-submit-btn').addEventListener('click', batchAddDomains);
});

// 加载已允许的域名列表
function loadAllowedDomains() {
  chrome.storage.sync.get(['allowedDomains'], (result) => {
    const domains = result.allowedDomains || [];
    const domainList = document.getElementById('domain-list');
    domainList.innerHTML = '';
    
    if (domains.length === 0) {
      domainList.innerHTML = `
        <li class="p-4 text-center text-gray-500 italic">
          暂无允许的域名
        </li>
      `;
      return;
    }
    
    domains.forEach((domain, index) => {
      const li = document.createElement('li');
      li.className = 'flex items-center justify-between p-3 border-b border-gray-200 hover:bg-gray-50 transition-colors';
      
      // 显示原始域名（不显示/*）
      li.innerHTML = `
        <div class="flex items-center space-x-2">
          <i class="fa fa-globe text-gray-400"></i>
          <span class="truncate">${domain}</span>
        </div>
        <button class="delete-btn p-1.5 rounded-full hover:bg-red-100 text-red-500 transition-colors" data-index="${index}">
          <i class="fa fa-trash"></i>
        </button>
      `;
      
      domainList.appendChild(li);
    });
    
    // 添加删除按钮事件
    document.querySelectorAll('.delete-btn').forEach(btn => {
      btn.addEventListener('click', deleteDomain);
    });
  });
}

// 添加新域名
function addDomain() {
  const input = document.getElementById('domain-input');
  let domain = input.value.trim();
  
  if (!domain) {
    showNotification('请输入域名', 'error');
    return;
  }
  
  // 确保URL格式正确（添加协议如果没有）
  if (!domain.startsWith('http://') && !domain.startsWith('https://')) {
    domain = 'https://' + domain;
  }
  
  // 规范化URL，移除末尾斜杠
  domain = normalizeUrl(domain);
  
  // 检查是否已存在
  chrome.storage.sync.get(['allowedDomains'], (result) => {
    const domains = result.allowedDomains || [];
    
    if (domains.includes(domain)) {
      showNotification('该域名已在允许列表中', 'warning');
      return;
    }
    
    // 添加到存储
    domains.push(domain);
    chrome.storage.sync.set({ allowedDomains: domains }, () => {
      showNotification('已添加域名', 'success');
      input.value = '';
      loadAllowedDomains();
    });
  });
}

// 删除域名
function deleteDomain() {
  const index = parseInt(this.getAttribute('data-index'));
  
  chrome.storage.sync.get(['allowedDomains'], (result) => {
    const domains = result.allowedDomains || [];
    const domainToDelete = domains[index];
    
    // 确认删除
    if (confirm(`确定要删除 "${domainToDelete}" 吗？`)) {
      domains.splice(index, 1);
      
      chrome.storage.sync.set({ allowedDomains: domains }, () => {
        showNotification('已删除域名', 'info');
        loadAllowedDomains();
      });
    }
  });
}

// 切换批量添加模式
function toggleBatchMode() {
  const batchContainer = document.getElementById('batch-add-container');
  const isVisible = batchContainer.classList.contains('hidden') ? false : true;
  
  if (isVisible) {
    batchContainer.classList.add('hidden');
  } else {
    batchContainer.classList.remove('hidden');
    document.getElementById('batch-domains').focus();
  }
}

// 批量添加域名
function batchAddDomains() {
  const textarea = document.getElementById('batch-domains');
  const domainText = textarea.value.trim();
  
  if (!domainText) {
    showNotification('请输入域名列表', 'error');
    return;
  }
  
  // 分割并处理每个域名
  const lines = domainText.split('\n');
  let validDomains = [];
  
  lines.forEach(line => {
    const domain = line.trim();
    if (domain) {
      // 确保URL格式正确
      let formattedDomain = domain;
      if (!formattedDomain.startsWith('http://') && !formattedDomain.startsWith('https://')) {
        formattedDomain = 'https://' + formattedDomain;
      }
      
      // 规范化URL
      formattedDomain = normalizeUrl(formattedDomain);
      validDomains.push(formattedDomain);
    }
  });
  
  // 去重
  validDomains = [...new Set(validDomains)];
  
  if (validDomains.length === 0) {
    showNotification('没有找到有效的域名', 'error');
    return;
  }
  
  // 添加到存储
  chrome.storage.sync.get(['allowedDomains'], (result) => {
    const existingDomains = result.allowedDomains || [];
    const newDomains = validDomains.filter(domain => !existingDomains.includes(domain));
    
    if (newDomains.length === 0) {
      showNotification('所有域名已在允许列表中', 'warning');
      return;
    }
    
    const updatedDomains = [...existingDomains, ...newDomains];
    
    chrome.storage.sync.set({ allowedDomains: updatedDomains }, () => {
      showNotification(`已添加 ${newDomains.length} 个域名`, 'success');
      textarea.value = '';
      toggleBatchMode();
      loadAllowedDomains();
    });
  });
}

// 规范化URL，移除末尾斜杠
function normalizeUrl(url) {
  try {
    const urlObj = new URL(url);
    return `${urlObj.origin}${urlObj.pathname}`.replace(/\/$/, '');
  } catch (e) {
    console.error('解析URL失败:', e);
    return url;
  }
}

// 显示通知
function showNotification(message, type) {
  const notification = document.createElement('div');
  notification.className = `fixed top-4 right-4 px-4 py-3 rounded-lg shadow-lg z-50 transition-all duration-300 transform ${
    type === 'success' ? 'bg-green-500 text-white' : 
    type === 'error' ? 'bg-red-500 text-white' : 
    type === 'warning' ? 'bg-yellow-500 text-white' :
    'bg-blue-500 text-white'
  }`;
  
  notification.innerHTML = `
    <div class="flex items-center">
      <i class="fa ${
        type === 'success' ? 'fa-check-circle' : 
        type === 'error' ? 'fa-exclamation-circle' : 
        type === 'warning' ? 'fa-exclamation-triangle' :
        'fa-info-circle'
      } mr-2"></i>
      <span>${message}</span>
    </div>
  `;
  
  document.body.appendChild(notification);
  
  // 2秒后自动消失
  setTimeout(() => {
    notification.style.opacity = '0';
    notification.style.transform = 'translateX(20px)';
    setTimeout(() => {
      document.body.removeChild(notification);
    }, 300);
  }, 3000);
}